import { LoadingOutlined, PlusOutlined, DownOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Modal, FormInstance, Row, Col, Upload, Tag, Menu, Dropdown } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, connect, ConnectProps } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect, ProFormDatePicker } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import UpdateForm from './components/UpdateForm';
import UpdateAuth from './components/UpdateAuth';
import OrganizeTree from './components/OrganizeTree';
import ResetPwd from './components/ResetPwd';
import MangeOrganize from './components/MangeOrganize';

import type { TableListItem } from './data.d';
import { upload } from '../../common/upload/service';
import { queryData, updateData, addData, removeData, updateAuth, updateStatus, updatePwd } from './service';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    console.log(fields)
    await addData({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在配置');
  try {
    await updateData(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleRemoveOne = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    let params = [selectedRow.id]
    await removeData({
      ids: params,
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleUpdateStatus = async (id: string, status: string) => {
  const hide = message.loading('正在更新状态');
  try {
    await updateStatus(id, status);
    message.success('状态更新成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('状态更新失败，请重试');
    return false;
  }
};

const handleUpdateAuth = async (value: any) => {
  const hide = message.loading('正在配置');
  try {
    await updateAuth({ ...value });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

function beforeUpload(file: any) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export type GlobalTableProps = {
  currentUser?: CurrentUser;
} & Partial<ConnectProps>;

const TableList: React.FC<GlobalTableProps> = (props) => {
  const formTableRef = useRef<FormInstance>();
  const formRef = useRef<FormInstance>();
  const childref = useRef();

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  /** 权限分配窗口的弹窗 */
  const [authModalVisible, handleAuthModalVisible] = useState<boolean>(false);
  /** 密码重置窗口的弹窗 */
  const [resetPwdModalVisible, handleResetPwdModalVisible] = useState<boolean>(false);
  const [operaFlag, handleoperaFlag] = useState<string>('0');
  /** 组织管理窗口的弹窗 */
  const [manageOrganizeModalVisible, handleManageOrganizeModalVisible] = useState<boolean>(false);
  /**显示详情 */
  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  //选中树形
  const [selectOrganize, setSelectOrganize] = useState<any>();
  const [organizeName, setOrganizeName] = useState<any>();
  //上传
  const [loading, setLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [fileIds, setFileIds] = useState<string>();

  /** 国际化配置 */
  const intl = useIntl();
  const { currentUser } = props;

  const uploadImage = async (file: any) => {
    setLoading(true);
    const formData = new FormData();
    formData.append("file", file.file);
    await upload(formData).then(res => {
      setLoading(false);
      setImageUrl(res.data.show_file_path)
      setFileIds(res.data.id)
    })
  }

  const handleChange = async (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl: any) => {
        setLoading(true);
        setImageUrl(imageUrl);
      });
    }
  }


  const columns: ProColumns<TableListItem>[] = [
    {
      title: (
        <FormattedMessage
          id="登录名"
          defaultMessage="登录名"
        />
      ),
      dataIndex: 'login_name',
      tip: '登录名',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="姓名" defaultMessage="姓名" />,
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="性别" defaultMessage="性别" />,
      dataIndex: 'sex',
      hideInForm: true,
      valueEnum: {
        1: {
          text: (
            <FormattedMessage id="男" defaultMessage="男" />
          ),
          status: 'Success',
        },
        2: {
          text: (
            <FormattedMessage id="女" defaultMessage="女" />
          ),
          status: 'Processing',
        },
        3: {
          text: (
            <FormattedMessage id="未知" defaultMessage="未知" />
          ),
          status: 'Processing',
        },
      },
    },
    {
      title: <FormattedMessage id="状态" defaultMessage="状态" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage id="启用" defaultMessage="启用" />
          ),
          status: 'Success',
        },
        1: {
          text: (
            <FormattedMessage id="禁用" defaultMessage="禁用" />
          ),
          status: 'Processing',
        },
        2: {
          text: (
            <FormattedMessage id="休眠" defaultMessage="休眠" />
          ),
          status: 'Processing',
        },
      },
    },
    {
      title: <FormattedMessage id="排序" defaultMessage="排序" />,
      dataIndex: 'order_by',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="创建时间" defaultMessage="创建时间" />,
      dataIndex: 'create_time',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width: '280px',
      valueType: 'option',
      render: (_, record) => [
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('user:edit') ? 'block' : 'none' }}
          onClick={() => {
            record.organize_name = selectOrganize.name;
            record.organize_id = selectOrganize.id;
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}>
          编辑
       </Button>,
        <Button type="primary" size='small' danger
          style={{ display: currentUser?.authButton.includes('user:del') ? 'block' : 'none' }}
          onClick={async () => {
            Modal.confirm({
              title: '删除任务',
              content: '确定删除该任务吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                const success = handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}>
          删除
      </Button>,
        <Button type="primary" size='small' style={{ display: (record.status == '0' && currentUser?.authButton.includes('user:status')) ? 'block' : 'none' }} danger onClick={() => {
          const success = handleUpdateStatus(record.id, '1');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          禁用
    </Button>,
        <Button type="primary" size='small' style={{ display: (record.status == '1' && currentUser?.authButton.includes('user:status')) ? 'block' : 'none' }} onClick={() => {
          const success = handleUpdateStatus(record.id, '0');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          启用
  </Button>,
        <Dropdown overlay={() => {
          return (
            <Menu>
              <Menu.Item key="0">
                <a
                  style={{ display: currentUser?.authButton.includes('user:resetPwd') ? 'block' : 'none' }}
                  onClick={() => {
                    handleoperaFlag('0');
                    handleResetPwdModalVisible(true);
                    setCurrentRow(record);
                  }}>密码重置</a>
              </Menu.Item>
              <Menu.Item key="1">
                <a
                  style={{ display: currentUser?.authButton.includes('user:assignAuth') ? 'block' : 'none' }}
                  onClick={() => {
                    handleAuthModalVisible(true);
                    setCurrentRow(record);
                  }}>权限分配</a>
              </Menu.Item>
              <Menu.Divider />
              <Menu.Item key="3">
                <a
                  style={{ display: currentUser?.authButton.includes('user:resetOrganize') ? 'block' : 'none' }}
                  onClick={() => {
                    handleManageOrganizeModalVisible(true);
                    setCurrentRow(record);
                  }}>设置组织</a>
              </Menu.Item>
            </Menu>
          )
        }}>
          <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
            更多<DownOutlined />
          </a>
        </Dropdown>
      ],
    },
  ];

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );


  const checkPassword = (rule: any, value: string) => {
    let login_password = formRef.current?.getFieldValue("login_password");
    if (value == login_password) { //校验条件自定义
      return Promise.resolve();
    }
    return Promise.reject('两次密码输入不一致');
  };


  return (
    <PageContainer>
      <div style={{ width: '20%', float: 'left' }}>
        <OrganizeTree myFef={childref} onSelect={async (value: any) => {
          setSelectOrganize(value);
          setOrganizeName(value.name)
          //查询列表数据
          if (actionRef.current) {
            formTableRef.current.submit();
          }
        }}></OrganizeTree>
      </div>
      <div style={{ width: '79%', float: 'right' }}>
        <ProTable<TableListItem>
          headerTitle={intl.formatMessage({
            id: 'pages.searchTable.title',
            defaultMessage: '用户信息',
          })}
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              style={{ display: currentUser?.authButton.includes('user:add') ? 'block' : 'none' }}
              onClick={() => {
                if (selectOrganize.id == '' || selectOrganize.id == null) {
                  message.warning('请选择左侧父级节点');
                } else {
                  formRef.current.setFieldsValue({
                    parent_name: selectOrganize.name,
                  });
                  handleModalVisible(true);
                }
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
          ]}
          request={
            (params, sorter, filter) => queryData({ ...params, organize_id: selectOrganize.id }).then(res => {
              const result = {
                data: res.data.rows,
                total: res.data.total,
                success: true
              }
              return result
            })
          }
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            style={{ display: currentUser?.authButton.includes('user:del') ? 'block' : 'none' }}
            onClick={async () => {
              Modal.confirm({
                title: '删除任务',
                content: '确定删除该任务吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const success = handleRemove(selectedRowsState);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            批量删除
          </Button>
          <Button type="primary" onClick={async () => {
            handleoperaFlag('1');
            handleResetPwdModalVisible(true);
          }}>
            批量密码重置
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: '新建用户',
          defaultMessage: '新建用户',
        })}
        width="900px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          if (value.sex) {
            value.sex = value.sex.value
          }
          const success = await handleAdd({ ...value, fileIds: fileIds, organize_id: selectOrganize.id, organize_name: selectOrganize.name } as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            formRef.current?.resetFields();
          }
        }}
      >

        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <Tag color="#2db7f5" style={{ height: '32px', lineHeight: '32px', fontSize: '16px', margin: '10px auto' }}>所属组织：{organizeName}</Tag>
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '登录账号',
                defaultMessage: '登录账号',
              })}
              rules={[
                {
                  required: true,
                  message: "登录账号不可为空。",
                },
              ]}
              width="xl"
              name="login_name"
              placeholder="请输入登录账号"
            />
          </Col>
          <Col span={12} order={1}>
            <ProFormText
              label={intl.formatMessage({
                id: '姓名',
                defaultMessage: '姓名',
              })}
              rules={[
                {
                  required: true,
                  message: "姓名不可为空。",
                },
              ]}
              width="xl"
              name="name"
              placeholder="请输入姓名"
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText.Password width="xl" name="login_password" label="登录密码" rules={[
              {
                required: true,
                message: "登录密码不可为空。",
              },
            ]} />
          </Col>
          <Col span={12} order={2}>
            <ProFormText.Password width="xl" name="confirm_password" label="确认密码" rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="确认密码"
                    defaultMessage="确认密码"
                  />
                ),
              },
              { validator: checkPassword }
            ]} />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormSelect
              width="xl"
              fieldProps={{
                labelInValue: true,
              }}
              request={async () => [
                { label: '男', value: '1' },
                { label: '女', value: '2' },
              ]}
              name="sex"
              label="性别"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '手机号',
                defaultMessage: '手机号',
              })}
              rules={[
                {
                  required: true,
                  message: '请输入手机号',
                },
                {
                  max: 11,
                  message: '最长11位!',
                },
                {
                  pattern: /^1[3|4|5|6|7|8|9]\d{9}$/,
                  message: '请输入正确的手机号',
                }
              ]}
              width="xl"
              name="phone"
              placeholder="请输入手机号"
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '邮箱',
                defaultMessage: '邮箱',
              })}
              width="xl"
              name="email"
              placeholder="请输入邮箱"
              rules={[
                {
                  type: 'email',
                  message: '请输入正确邮箱',
                  // pattern: /^[0-9]+$/,
                }
              ]}
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormDatePicker width="xl" name="birth_date" label="出生日期" placeholder="请输入出生日期" />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '座右铭',
                defaultMessage: '座右铭',
              })}
              width="xl"
              name="motto"
              placeholder="请输入座右铭"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '排序号',
                defaultMessage: '排序号',
              })}
              width="xl"
              name="order_by"
              placeholder="请输入排序号"
              rules={
                [
                  {
                    pattern: new RegExp(/^[1-9]\d*$/, "g"),
                    message: '只能输入数字'
                  }
                ]
              }
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '居住地址',
                defaultMessage: '居住地址',
              })}
              width="xl"
              name="live_address"
              placeholder="请输入居住地址"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '出生地址',
                defaultMessage: '出生地址',
              })}
              width="xl"
              name="birth_address"
              placeholder="请输入出生地址"
            />
          </Col>
        </Row>
        {/* <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <ProFormText
              label={intl.formatMessage({
                id: '职位',
                defaultMessage: '职位',
              })}
              width="xl"
              name="position"
              placeholder="请输入职位"
            />
          </Col>
        </Row> */}
        <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action=""
              customRequest={uploadImage}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <ProFormTextArea
              name="remark"
              label="备注"
              placeholder="请输入备注"
            />
          </Col>
        </Row>
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate({ ...value, id: currentRow?.id });
          // const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <UpdateAuth
        onSubmit={async (value: any) => {
          const success = await handleUpdateAuth({ ...value, id: currentRow?.id });
          if (success) {
            handleAuthModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleAuthModalVisible(false);
          setCurrentRow(undefined);
        }}
        authModalVisible={authModalVisible}
        values={currentRow || {}}
      />
      <ResetPwd
        onSubmit={async (value: any) => {
          if (operaFlag == '0') {//单条记录
            value = { ...value, ids: currentRow?.id };
          } else if (operaFlag == '1') {
            value = { ...value, ids: selectedRowsState.map((row) => row.id) };
          }
          const success = await updatePwd(value);
          if (success) {
            handleResetPwdModalVisible(false);
            setSelectedRows([]);
            setCurrentRow(undefined);
            message.success('密码重置成功。');
          }
        }}
        onCancel={() => {
          handleResetPwdModalVisible(false);
          setSelectedRows([]);
          setCurrentRow(undefined);
        }}
        resetPwdModalVisible={resetPwdModalVisible}
        values={currentRow || {}}
      />
      <MangeOrganize
        onSubmit={async (value: any) => {

        }}
        onCancel={() => {
          handleManageOrganizeModalVisible(false);
          setSelectedRows([]);
          setCurrentRow(undefined);
        }}
        manageOrganizeModalVisible={manageOrganizeModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

// export default TableList;
export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);